import React, { useEffect, useState, useCallback } from 'react';
import {
  Card,
  Space,
  Button,
  Table,
  TableColumnProps,
  Image,
  Popconfirm,
  Message,
} from '@arco-design/web-react';
import { default as useFetchList } from '@/hooks/getList';
import { getContentPage, updateContentHidden } from '@/api/article';
import Search from '@/pages/resources/article/search';
import { useHistory } from 'react-router-dom';
import { communityOptions, statusOptions } from '@/pages/resources/common';

function Article() {
  const history = useHistory();
  const [searchParams, setSearchParams] = useState({
    GetContentPageParam: {},
  });

  const { data, pagination, loading, getData } = useFetchList(
    getContentPage,
    searchParams
  );
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const onSearch = useCallback((values) => {
    const StartOn = values.CreatedTime
      ? new Date(values.CreatedTime[0]).toISOString()
      : null;
    const EndOn = values.CreatedTime
      ? new Date(values.CreatedTime[1]).toISOString()
      : null;

    const params = {
      GetContentPageParam: {
        Name: values.Name, //企业子账号
        Title: values.Title, //文章标题
        CommunityDataKey: values.CommunityDataKey, //社区
        StartOn, //开始时间
        EndOn, //结束时间
        ContentStatus: values.ContentStatus, //状态
      },
    };
    pagination.current = 1;
    setSearchParams(params);
    getData({ ...params, PageIndex: pagination.current });
  }, []);

  const onChangeTable = useCallback(
    (pagination) => {
      const { current, pageSize } = pagination;
      const obj = {
        PageIndex: current,
        PageSize: pageSize,
      };
      const newObj = Object.assign(obj, searchParams);
      getData(newObj);
    },
    [searchParams]
  );

  useEffect(() => {
    const params = {
      GetContentPageParam: {
        CommunityDataKey: 'CampusCommunity',
      },
    };
    getData(params);
  }, []);

  const columns: TableColumnProps[] = [
    {
      title: '序号',
      align: 'center',
      width: 50,
      render: (col, record: any, index: number) => index + 1,
    },
    {
      title: '封面图',
      dataIndex: 'CoverPic',
      align: 'center',
      render: (col, record: any) => (
        <Image src={record.CoverPic} width={100} alt="" />
      ),
    },
    {
      title: '文章编码',

      dataIndex: 'ContentCode',
      align: 'center',
    },
    {
      title: '校园账号编码',
      dataIndex: 'UserAccount',
      align: 'center',
    },
    {
      title: '校园账号',
      dataIndex: 'UserName',
      align: 'center',
    },
    {
      title: '文章标题',
      dataIndex: 'Title',
      align: 'center',
    },
    {
      title: '社区',
      dataIndex: 'CommunityDataKey',
      align: 'center',
      width: 100,
      render: (col, record: any) => {
        return communityOptions.find((opt) => opt.value === col)?.label;
      },
    },
    {
      title: '浏览量',
      dataIndex: 'VisitCount',
      align: 'center',
    },
    {
      title: '点赞量',
      dataIndex: 'LikeCount',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'ContentStatus',
      align: 'center',
      width: 90,
      render: (col, record: any) => {
        return statusOptions.find((opt) => opt.value === col)?.label;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'CreatedOn',
      align: 'center',
    },
    {
      title: '发布时间',
      dataIndex: 'PublishTime',
      align: 'center',
    },
    {
      title: '操作',
      dataIndex: 'opt',
      align: 'center',
      fixed: 'right',
      width: 220,
      render: (_, record) => (
        <Space>
          {record.ContentStatus === 0 && record.IsHidden && (
            <Button
              type="text"
              onClick={() => singleUpdateContent(false, record)}
            >
              显示
            </Button>
          )}
          {record.ContentStatus === 0 && !record.IsHidden && (
            <Button
              type="text"
              status="warning"
              onClick={() => singleUpdateContent(true, record)}
            >
              隐藏
            </Button>
          )}
          <Button type="text" onClick={() => toArticleDetail(record)}>
            查看详情
          </Button>
        </Space>
      ),
    },
  ];

  const updateContentVisible = useCallback(
    async (IsHidden: boolean, Ids: string[]) => {
      const res: any = await updateContentHidden({
        UpdateContentHiddenParam: {
          Ids,
          IsHidden,
        },
      });

      if (res.StatusCode === 200) {
        Message.success(res.Message);
        setSelectedRowKeys([]);
        getData();
      } else {
        Message.error(res.Message);
      }
    },
    [selectedRowKeys]
  );

  const singleUpdateContent = (IsHidden: boolean, record) => {
    updateContentVisible(IsHidden, [record.ID]);
  };

  const toArticleDetail = (record) => {
    const { ID } = record;
    history.push({
      pathname: '/resources/articleDetails',
      state: {
        ID,
      },
    });
  };

  return (
    <div>
      <Card>
        <Space size="medium">
          <Popconfirm
            position="bottom"
            focusLock
            title="提示"
            okText="确认"
            content="此操作将选择的贴文隐藏，请确认！"
            onOk={async () => {
              if (selectedRowKeys.length === 0) {
                Message.error({
                  content: '请选择需要隐藏的贴文',
                });
                return;
              }
              updateContentVisible(true, selectedRowKeys);
            }}
          >
            <Button type="primary" status="warning">
              批量隐藏
            </Button>
          </Popconfirm>
          <Popconfirm
            position="bottom"
            focusLock
            title="提示"
            okText="确认"
            content="此操作将选择的贴文显示到对应社区，请确认！"
            onOk={async () => {
              if (selectedRowKeys.length === 0) {
                Message.error({
                  content: '请选择需要显示的贴文',
                });
                return;
              }
              updateContentVisible(false, selectedRowKeys);
            }}
          >
            <Button type="primary">批量显示</Button>
          </Popconfirm>
        </Space>

        <Search
          statusOptions={statusOptions}
          communityOptions={communityOptions}
          onSearch={onSearch}
        ></Search>
      </Card>

      <Card style={{ marginTop: '20px' }}>
        <Table
          border
          rowKey="ID"
          borderCell
          columns={columns}
          data={data}
          pagination={pagination}
          loading={loading}
          scroll={{
            y: 400,
          }}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
              setSelectedRowKeys(selectedRowKeys);
            },
            checkboxProps: (record) => {
              return {
                disabled: record.IsForSystem,
              };
            },
          }}
          onChange={onChangeTable}
        ></Table>
      </Card>
    </div>
  );
}

export default Article;
